<template>
	<view class="login-container">
		<uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
		<!-- open-type属性绑定，希望授权，且从@getuserinfo获取用户基本信息 
		     open-type="getUserInfo"和@getuserinfo 是固定写法，
			 只有"getUserInfo"事件名称可以随意-->
		<button type="primary" open-type="getUserInfo" @getuserinfo="getUserInfo">一键登录</button>
		<text>登录后尽享更多权益</text>
	</view>
</template>

<script>
	import { mapMutations, mapState } from 'vuex'
	export default {
		name:"my-login",
		data() {
			return {
				
			};
		},
		computed: {
			...mapState('m_user', ['redirectInfo'])
		},
		methods: {
			...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateRedirectInfo']),
			// 用户授权后，获取用户基本信息
			getUserInfo(e) {
				// 判断是否获取用户信息成功
				if(e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$show.Msg('您取消了登录授权！')
				// 获取用户信息成功，e.detail.userInfo 就是用户的基本信息
				console.log(e.detail.userInfo)
				this.updateUserInfo(e.detail.userInfo)
				this.getToken(e.detail)
			},
			async getToken(info) {
				// 获取code值
				const [err, res] = await uni.login().catch(err=>err)
				// 判断是否wx.login()调用失败
				if(err || res.errMsg !== 'login:ok') return uni.$showError('登录失败!')
				const query = {
					code: res.code,
					encryptedData: info.encryptedData,
					iv: info.iv,
					rawData: info.rawData,
					signature: info.signature
				}
				// 获取token
				const { data } = await uni.$http.post('/api/public/v1/users/wxlogin', query)
				if(data.meta.status !== 200) return uni.$showMsg('登录失败!')
				uni.$showMsg('登录成功!')
				this.updateToken(data.message.token)
				this.navigateBack()
			},
			// 登录成功后返回上一个页面
			navigateBack() {
				if(this.redirectInfo && redirectInfo.openType === 'switchTab') {
					uni.switchTab({
						url: this.redirectInfo.from,
						complete: () => {
							this.updateRedirectInfo(null)
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
.login-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #f8f8f8;
	height: 750rpx;
	button {
		background-color: #c00000;
		width: 90%;
		border-radius: 100px;
	}
	text {
		font-size: 12px;
		color: gray;
		margin-top: 10px;
	}
}
</style>